package com.example.androidtest;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


/**
 * @author maxiaoyong
 */
public class MainActivity extends AppCompatActivity {

    private static final String TEXT = "我  是  中  国  人 = i  am  a  chinese";
    private AppCompatTextView textView;
    private SpannableStringBuilder spannableSb = new SpannableStringBuilder();
    /**
     * 汉字或单词点击前颜色
     * 这个色值最好提前给你布局文件中的TextView设置好，保证非汉字或单词的文本，例如特殊符号等颜色与其他文本一致
     */
    private int beforeColor;
    /**
     * 汉字或单词点击后颜色
     */
    private int afterColor;
    /**
     * 记录上一次被点击汉字或单词
     */
    private WordEntity lastClickWord;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setTextClickable();
    }

    private void initView() {
        this.textView = findViewById(R.id.AppCompatTextView);
    }

    private void setTextClickable() {

        this.beforeColor = getResources().getColor(android.R.color.darker_gray);
        this.afterColor = getResources().getColor(android.R.color.holo_red_dark);

        this.spannableSb.append(TEXT);
        // 获取文本中汉字和单词集合
        List<WordEntity> wordEntityList = recordWordIndex(TEXT);
        // 给文本中每个汉字和单词添加点击效果
        for (int i = 0; i < wordEntityList.size(); i++) {
            this.spannableSb.setSpan(new SpannableStyle(wordEntityList.get(i), false),
                    wordEntityList.get(i).getStartIndex(),
                    wordEntityList.get(i).getEndIndex(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        // 将SpannableStringBuilder设置给TextView
        this.textView.setText(this.spannableSb);
        // 去掉点击文本时文字高亮背景效果
        this.textView.setHighlightColor(getResources().getColor(android.R.color.transparent));
        // 使TextView文本点击效果生效
        this.textView.setMovementMethod(LinkMovementMethod.getInstance());
    }


    /**
     * 记录每个文字和单词开始序列和
     *
     * @param text 文本内容
     */
    private List<WordEntity> recordWordIndex(String text) {

        List<WordEntity> wordEntityList = new ArrayList<>();
        List<String> words = new ArrayList<>();
        words.addAll(Util.splitChinese(text));
        words.addAll(Util.splitWord(text));

        // 文本检索起始序列，每次检索成功后更新
        int beginIndex = 0;
        for (int i = 0; i < words.size(); i++) {
            String word = words.get(i);
            // 检索该文字所在文本起点index与终点index
            // 每次检索都从上一次检索结束的index开始，避免文本中存在重复单词或文字，出现重复情况
            int startIndex = text.indexOf(word, beginIndex);
            int endIndex = startIndex + word.length();
            // 将汉字或单词以及所在文本中起终点index组合成WordEntity，并保存到集合中
            WordEntity wordEntity = new WordEntity();
            wordEntity.setWord(words.get(i));
            wordEntity.setStartIndex(startIndex);
            wordEntity.setEndIndex(endIndex);
            wordEntityList.add(wordEntity);
            // 记录本次检索结束index
            beginIndex = endIndex;
        }
        return wordEntityList;
    }

    private class SpannableStyle extends ClickableSpan {

        private WordEntity wordEntity;
        private boolean isClicked;

        private SpannableStyle(WordEntity wordEntity, boolean isClicked) {
            this.wordEntity = wordEntity;
            this.isClicked = isClicked;
        }

        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
            if (isClicked) {
                ds.setColor(afterColor);
            } else {
                ds.setColor(beforeColor);
            }
        }

        @Override
        public void onClick(@NonNull View widget) {
            // 重复点击，不做任何操作
            if (MainActivity.this.lastClickWord == this.wordEntity) {
                return;
            }
            // 更新当前被点击的汉字或单词
            MainActivity.this.spannableSb.setSpan(new SpannableStyle(this.wordEntity, true),
                    this.wordEntity.getStartIndex(),
                    this.wordEntity.getEndIndex(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 更新上一次被点击的汉字或单词
            if (MainActivity.this.lastClickWord != null) {
                MainActivity.this.spannableSb.setSpan(new SpannableStyle(MainActivity.this.lastClickWord, false),
                        MainActivity.this.lastClickWord.getStartIndex(),
                        MainActivity.this.lastClickWord.getEndIndex(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            MainActivity.this.textView.setText(MainActivity.this.spannableSb);
            MainActivity.this.lastClickWord = this.wordEntity;
            Util.showToast(MainActivity.this, this.wordEntity.getWord(), Toast.LENGTH_SHORT);
        }
    }
}